package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;

import org.eclipse.emf.ecore.util.EcoreUtil;

import it.univaq.mancoosi.mancoosimm.Alternative;
import it.univaq.mancoosi.injectors.systemconfiguration.managers.AlternativesManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;

public class UbuntuAlternativesManager extends AlternativesManager{

	protected int alternativesNumber = 0;

	public static AlternativesManager getInstance() {
		if (INSTANCE == null)
			INSTANCE = new UbuntuAlternativesManager();
		return INSTANCE;
	}


	public Alternative getAlternative(String alternativeName){
		//TODO
		return null;
	};

	public Boolean exists(String alternativeName){
		return this.alternativeMap.containsKey(alternativeName);
	};

	public void createAlternativesFromSystem() {
		syncMap();
		Alternative newAlternative;
		String line;

		try {
			String[] cmd = {"/bin/sh","-c","ls --time-style=long-iso -l /etc/alternatives | awk '{print $8 \" -> \"  $10}'"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd);	

			line = input.readLine(); //This is to do not consider the first line which is something like "total 32"
			while ((line = input.readLine()) != null) {
			String[] elements = line.split(" -> ");
				if  (elements.length > 1) {
					alternativesNumber++;
					String name = elements[0];
					if (!exists(name)) {	
						newAlternative = factory.createAlternative();
						newAlternative.setName(name);
						newAlternative.setCurrent(UbuntuFileSystemManager.getInstance().createFile(elements[1]));
						this.alternativeMap.put(name, newAlternative);
						UbuntuEnvironmentManager.getInstance().getEnvironment().getAlternatives().add(newAlternative);
					}
				}
			}

			input.close();

		} catch (Exception err) {
			err.printStackTrace();
		}		

	}

	public  void synchronize() {
		createAlternativesFromSystem();
		
		//check whether there have been changes in the number of alternatives
//		int numAltInTheModel = 0;
//		if(UbuntuEnvironmentManager.getInstance().getEnvironment() != null){
//			numAltInTheModel = UbuntuEnvironmentManager.getInstance().getEnvironment().getAlternatives().size();
//		}
//		int numAddedAlt = addedAlternativesAfterSync;
//
		int altInTheSystem = alternativesNumber;
		
		if(!((this.alternativeMap.size()) == altInTheSystem)){		
			Iterator<Alternative> iterator = this.alternativeMap.values().iterator();
			while (iterator.hasNext()) {
				Alternative curr = iterator.next();
				if (curr.getCurrent().isIsMissing()) {
					this.alternativeMap.remove(curr);
					EcoreUtil.delete(curr);
					UbuntuFileSystemManager.getInstance().deleteFile(curr.getCurrent());
				}
			}
		}
	}

}

